package com.hourses.controller;

import com.alibaba.fastjson2.JSON;
import com.hourses.dto.AssignRoleIdAuthIdsDto;
import com.hourses.page.Page;
import com.hourses.pojo.CurrentUser;
import com.hourses.pojo.Result;
import com.hourses.pojo.Role;
import com.hourses.pojo.RoleAuth;
import com.hourses.service.impl.RoleServiceImpl;
import com.hourses.utils.TokenUtils;
import com.hourses.utils.WarehouseConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description:
 * @Author:LiTao
 * @Date:2025/4/29 14:25
 */
//与用户角色相关的控制器
@RestController
@RequestMapping("/role")
public class RoleController {
    //获取数据库当中所有角色的接口  /role-list
    @Autowired
    private RoleServiceImpl roleService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @GetMapping("/role-list")
    public Result roleList(){
        List<Role> roles = roleService.selectAllRoles();
        redisTemplate.opsForValue().set("allRoles:", JSON.toJSONString(roles));
        return Result.ok(roles);
    }


    //获取角色列表  http://localhost:3000/api/role/role-page-list?roleName=&roleCode=&roleState=&pageSize=5&pageNum=1&totalNum=0
    @GetMapping("/role-page-list")
    public Result roleListPage(Role role, Page page){
        Page roleList = roleService.getRolestPage(role, page);
        return Result.ok(roleList);
    }

    //添加角色    http://localhost:3000/api/role/role-add
    @Autowired
    private TokenUtils tokenUtils;
    @PostMapping("/role-add")
    public Result addRoles(@RequestBody Role role, @RequestHeader(WarehouseConstants.HEADER_TOKEN_NAME) String token){
        CurrentUser currentUser = tokenUtils.getCurrentUser(token);
        role.setCreateBy(currentUser.getUserId());
        Result result = roleService.addRole(role);
        return result;
    }


    //启用角色    http://localhost:3000/api/role/role-state-update
    @RequestMapping("/role-state-update")
    public Result startOrCloseRole(@RequestBody Role role){
        Result result = roleService.startOrCloseRole(role);
        return result;
    }

    //根据roleId删除角色    http://localhost:3000/api/role/role-delete/18
    @RequestMapping("/role-delete/{roleId}")
    public Result deleteRoleById(@PathVariable Integer roleId){
        Result result = roleService.deleteRoleById(roleId);
        return result;
    }

    //根据roleId查询auths  http://localhost:3000/api/role/role-auth?roleId=2
    @GetMapping("/role-auth")
    public Result selectAuthIdsByRoleId(@RequestParam("roleId")Integer roleId){
        List<Integer> authIdList = roleService.selectAuthIdsByRoleId(roleId);
        return Result.ok(authIdList);
    }

    //修改角色权限  http://localhost:3000/api/role/auth-grant
    @Transactional   //添加事务
    @RequestMapping("/auth-grant")
    public Result updateRoleAuths(@RequestBody AssignRoleIdAuthIdsDto assignRoleIdAuthIdsDto){
        //step1:现根据roleId删除角色的所有权限
        Integer count = roleService.deleteAuthsByRoleId(assignRoleIdAuthIdsDto.getRoleId());
        //上面的操作不做判断，避免某些新增角色还没有添加过权限
        //step2:再将list中的auth给该角色加上去
        //先创建一个roleAuth对象，待会儿直接往表中insert就可以了
        RoleAuth roleAuth = new RoleAuth();
        //给roleAuth对象的roleId属性赋值
        roleAuth.setRoleId(assignRoleIdAuthIdsDto.getRoleId());
        Integer insertCount = 0;
        if(assignRoleIdAuthIdsDto.getAuthIds()!=null&&assignRoleIdAuthIdsDto.getAuthIds().size()>0){
            for (Integer authId:assignRoleIdAuthIdsDto.getAuthIds()){
                //给roleAuth对象的authId赋值
                roleAuth.setAuthId(authId);
                //执行insert操作
                insertCount += roleService.insertRoleAuth(roleAuth);
            }
            if (insertCount==assignRoleIdAuthIdsDto.getAuthIds().size()){
                return Result.ok("修改成功！");
            }
        }else {
            return Result.ok("修改成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"修改失败！请联系管理员...");
    }


    //修改角色信息   http://localhost:3000/api/role/role-update
    @RequestMapping("/role-update")
    public Result upadateRoleDesc(@RequestBody Role role){
        Result result = roleService.updateRoleDesc(role);
        return result;
    }
}
